package com.bookmanger.server.service.impl;

import com.bookmanger.common.exception.BaseException;
import com.bookmanger.pojo.DTO.CheckInfoDTO;
import com.bookmanger.pojo.DTO.UserRegisterDTO;
import com.bookmanger.pojo.Entity.AdminEntity;
import com.bookmanger.pojo.Entity.Reader;
import com.bookmanger.pojo.Entity.UserEntity;
import com.bookmanger.server.mapper.UserMapper;
import com.bookmanger.server.service.UserService;
import com.bookmanger.utils.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public Reader loginReader(String username, String password) {
            return userMapper.findByUsernameAndPassword4Reader(username, MD5Util.getMD5String(password));
    }

    public AdminEntity loginAdmin(String username, String password) {
        return userMapper.findByUsernameAndPassword4Admin(username, MD5Util.getMD5String(password));
    }

    @Override
    public void checkInfo(CheckInfoDTO checkInfoDTO) {
        String findInfo;
        if(checkInfoDTO.getType().equals("reader_number")||checkInfoDTO.getType().equals("email")||checkInfoDTO.getType().equals("phone_number")){
            findInfo = userMapper.checkInfo(checkInfoDTO);
        }else{
            throw new BaseException("信息验证类别错误!");
        }
        if(findInfo!=null){
            String errorMessage = String.format("%s已被使用!", checkInfoDTO.getType());
            throw new BaseException(errorMessage);
        }
    }

    @Override
    public boolean registerByEmail(UserRegisterDTO userRegisterDTO) {
        Reader reader = Reader.builder()
                .readerNumber(userRegisterDTO.getReaderNumber())
                .password(MD5Util.getMD5String(userRegisterDTO.getPassword()))
                .name(userRegisterDTO.getName())
                .department(userRegisterDTO.getDepartment())
                .major(userRegisterDTO.getMajor())
                .grade(userRegisterDTO.getGrade())
                .phoneNumber(userRegisterDTO.getPhoneNumber())
                .email(userRegisterDTO.getEmail())
                .gender(userRegisterDTO.getGender())
                .status(0)
                .applyDate(LocalDate.now())
                .build();
        return userMapper.registerByEmail(reader);
    }
}
